//
//  SegmentedControl.m
//  mmbang
//
//  Created by 肖信波 on 13-8-31.
//  Copyright (c) 2013年 iyaya. All rights reserved.
//

#import "SegmentedControl.h"
#import "SDWebImageManager.h"
#import "UIButton+WebCache.h"
#import "SegmentBtn.h"

#define kFlowViewHeightRadio 1 / 12.0f

#define kSeparatorMarginTop 7.0f
#define kFlowViewMarginLeft 0.0f

@implementation SegmentedControl

- (void)initResoureViewWithVerSpace:(NSNumber*)verSpace {
    _flowView = [[UIView alloc] init];
    _flowView.backgroundColor = self.selectedFlowColor;
    _flowView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self addSubview:_flowView];

    for (NSString *title in _titles) {
        SegmentBtn *button = [SegmentBtn buttonWithType:UIButtonTypeCustom];
        [button setTitle:title forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchDown];
        button.backgroundColor = [UIColor clearColor];
        button.titleLabel.font = [TKFont boldSystemFontOfSize:12.0f];
        
        if (verSpace)
        {
            button.verSpace =verSpace;

        }
        [self addSubview:button];
        [_buttons addObject:button];
    }
    
    _separatorViews = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < _titles.count - 1; i++) {
        UIView *separatorView = [[UIView alloc] init];
        separatorView.backgroundColor = RGBA_COLOR(245.0f, 245.0f, 245.0f, 1.0f);
        [self addSubview:separatorView];
        [_separatorViews addObject:separatorView];
    }
    
    if (_buttons.count > 0) {
        [self selectWithIndex:0];
    }
    [self setShadowPosition:SegmentedControlShadowPositionBottom];
}

- (id)initWithTitles:(NSArray *)titles andVerSpace:(float)verSpace {
    self = [super init];
    if (self) {
        self.titles = titles;
        self.selectedFlow = YES;
        self.backgroundColor = COLOR_NAV_BACKGROUND;
        _buttons = [[NSMutableArray alloc] init];
        self.selectedFlowColor = COLOR_PINK;
        [self initResoureViewWithVerSpace:[NSNumber numberWithFloat:verSpace]];
    }
    return self;
}

- (id)initWithTitles:(NSArray *)titles {
    self = [super init];
    if (self) {
        self.titles = titles;
        self.selectedFlow = YES;
        self.backgroundColor = COLOR_NAV_BACKGROUND;
        _buttons = [[NSMutableArray alloc] init];
        self.selectedFlowColor = COLOR_PINK;
        [self initResoureViewWithVerSpace:nil];
    }
    return self;
}

- (void)selectWithIndex:(NSInteger)index {
    if (_selectedIndex < _buttons.count) {
        SegmentBtn *lastselectedButton = [_buttons objectAtIndex:_selectedIndex];
        [lastselectedButton setEnabled:YES];
    }
    _selectedIndex = index;
        
    SegmentBtn *selectedButton = [_buttons objectAtIndex:index];
    [selectedButton setEnabled:NO];
    
    if (self.selectedFlow) {
        [UIView beginAnimations:@"flow" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect frame = _flowView.frame;
            frame.origin.x = CGRectGetMinX(selectedButton.frame) + kFlowViewMarginLeft;
            if (self.customFlowFrame) {
                frame = self.customFlowRectInButton;
                frame.origin.x = CGRectGetMinX(selectedButton.frame) + self.customFlowRectInButton.origin.x;
            }
            
            _flowView.frame = frame;
        } completion:^(BOOL finished) {
            if (finished) {
                
            }
        }];
        
        [UIView commitAnimations];
    }
}

- (NSString *)getSelectedTitle {
    return [self.titles objectAtIndex:_selectedIndex];
}

- (void)buttonTouched:(UIButton *)button {
    [self selectWithIndex:[_buttons indexOfObject:button]];
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

- (void)setFrame:(CGRect)frame {
    CGRect backupFrame = self.frame;
    [super setFrame:frame];
    
    if (CGSizeEqualToSize(backupFrame.size, frame.size)){
        return;
    }
    
    [self adjustSubViewsFrame];
}

- (void)upadateButtons:(NSArray*)titles andVerSpace:(NSNumber*)verSpace {
    [_buttons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [(SegmentBtn*)obj removeFromSuperview];
    }];
    _titles = titles;
    _buttons = [[NSMutableArray alloc] init];
    for (NSString *title in _titles) {
        SegmentBtn *button = [SegmentBtn buttonWithType:UIButtonTypeCustom];
        [button setTitle:title forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchDown];
        button.backgroundColor = [UIColor clearColor];
        button.titleLabel.font = [TKFont boldSystemFontOfSize:12.0f];
        
        if (verSpace)
        {
            button.verSpace =verSpace;
            
        }
        [self addSubview:button];
        [_buttons addObject:button];
    }
    
    if (!_separatorHidden) {
        [_separatorViews enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [(UIView*)obj removeFromSuperview];
            
        }];
        _separatorViews = [[NSMutableArray alloc] init];
        
        for (int i = 0; i < _titles.count - 1; i++) {
            UIView *separatorView = [[UIView alloc] init];
            separatorView.backgroundColor = RGBA_COLOR(245.0f, 245.0f, 245.0f, 1.0f);
            [self addSubview:separatorView];
            [_separatorViews addObject:separatorView];
        }
    }
    [self adjustSubViewsFrame];
}

- (void)adjustSubViewsFrame {
    CGRect frame = self.bounds;
    CGFloat width = frame.size.width / _buttons.count;
    CGFloat flowHeight = self.frame.size.height * kFlowViewHeightRadio;
    
    for (int i = 0 ; i < _buttons.count; i++) {
        SegmentBtn *button = [_buttons objectAtIndex:i];
        button.frame = CGRectMake(i * width, 0, width, frame.size.height-(self.selectedFlow?flowHeight:0));
    }
    
    for (int i = 0; i < _separatorViews.count; i++) {
        UIView *separatorView = [_separatorViews objectAtIndex:i];
        separatorView.frame = CGRectMake((i + 1) * width - 1.0f, kSeparatorMarginTop, 1.0f, self.frame.size.height - kSeparatorMarginTop * 2);
    }
    
    if (!self.customFlowFrame) {
        _flowView.frame = CGRectMake(self.selectedIndex * width + kFlowViewMarginLeft, frame.size.height - flowHeight, width - 2 * kFlowViewMarginLeft, flowHeight);
    }else{
        CGRect flowFrame = self.customFlowRectInButton;
        flowFrame.origin.x = self.selectedIndex * width + self.customFlowRectInButton.origin.x;
        _flowView.frame = flowFrame;
    }
    self.shadowPosition = self.shadowPosition;
}


#pragma mark -
- (void)setSelectedIndex:(NSInteger)selectedIndex {
    if (_selectedIndex == selectedIndex) {
        return;
    }
    [self selectWithIndex:selectedIndex];
}

- (void)setIcons:(NSArray *)icons {
    _icons = icons;
    if (icons.count == _buttons.count) {
        for (int i = 0; i < icons.count; i++) {
            UIImage *icon = [icons objectAtIndex:i];
            SegmentBtn *button = [_buttons objectAtIndex:i];
            [button setImage:icon forState:UIControlStateNormal];
            [button setImage:icon forState:UIControlStateHighlighted];
        }
    }
}

- (void)setHighlightIcons:(NSArray *)highlightIcons {
    _highlightIcons = highlightIcons;
    if (highlightIcons.count == _buttons.count) {
        for (int i = 0; i < _highlightIcons.count; i++) {
            UIImage *icon = [highlightIcons objectAtIndex:i];
            SegmentBtn *button = [_buttons objectAtIndex:i];
            [button setImage:icon forState:UIControlStateDisabled];
            [button setImage:icon forState:UIControlStateHighlighted];
        }
    }
}

- (void)dynamicSetIcons:(NSArray *)icons highlight:(NSArray *)highlightedIcons placeHolders:(NSArray *)placeHolders highlightedPlaceHolders:(NSArray *)highlightedPlaceHolders imageSize:(CGSize)imageSize {
    _icons = icons;
    _highlightIcons = highlightedIcons;
    if (icons.count == _buttons.count) {
        for (int i = 0; i < icons.count; i++) {
            NSURL *icon = [NSURL URLWithString:icons[i]];
            NSURL *highlightedIcon = [NSURL URLWithString:highlightedIcons[i]];
            UIImage *placeHolder = [UIImage imageNamed:placeHolders[i]];
            UIImage *highlightedPlaceHolder = [UIImage imageNamed:highlightedPlaceHolders[i]];
            
            SegmentBtn *button = _buttons[i];
            button.imageSize = imageSize;
            
            kWeakObj(button);
            
            NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:icon];
            UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
            if (lastPreviousCachedImage) {
                placeHolder = lastPreviousCachedImage;
            }
            //set the default image before the first block action come back in case the network is slow, and the normal image is blank during this time
            [button setImage:placeHolder forState:UIControlStateNormal];
            [button setImage:highlightedPlaceHolder forState:UIControlStateDisabled];

            [button sd_setImageWithURL:highlightedIcon forState:UIControlStateDisabled placeholderImage:highlightedPlaceHolder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                //Note here:
                //1 sdwebimage don't scale the image, we have to do it by ourselves. Suppose the image we uploaded in server is scale 2
                //2 setImage will reset pending calls, so we have to ensure the first set successfully before we luanch the second
                if (image) {
                    [weakObj setImage:[UIImage imageWithCGImage:image.CGImage scale:2 orientation:image.imageOrientation] forState:UIControlStateDisabled];
                }
                [weakObj sd_setImageWithURL:icon forState:UIControlStateNormal placeholderImage:placeHolder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType,NSURL *imageURL) {
                    if (image) {
                        [weakObj setImage:[UIImage imageWithCGImage:image.CGImage scale:2 orientation:image.imageOrientation] forState:UIControlStateNormal];
                    }
                }];
            }];
        }
    }
}

- (void)setTitleColor:(UIColor *)titleColor {
    _titleColor = titleColor;
    for (SegmentBtn *button in _buttons) {
        [button setTitleColor:titleColor forState:UIControlStateNormal];
    }
}

- (void)setSelectedTitleColor:(UIColor *)selectedTitleColor {
    _selectedTitleColor = selectedTitleColor;
    for (SegmentBtn *button in _buttons) {
        [button setTitleColor:selectedTitleColor forState:UIControlStateDisabled];
        [button setTitleColor:selectedTitleColor forState:UIControlStateHighlighted];
    }
}

- (void)setTitleFont:(UIFont *)titleFont {
    _titleFont = titleFont;
    for (SegmentBtn *button in _buttons) {
        [button.titleLabel setFont:titleFont];
    }
}

- (void)setTitleInsets:(UIEdgeInsets)titleInsets {
    _titleInsets = titleInsets;
    for (SegmentBtn *button in _buttons) {
        [button setTitleEdgeInsets:titleInsets];
    }
}

- (void)setImageInsets:(UIEdgeInsets)imageInsets {
    _imageInsets = imageInsets;
    for (SegmentBtn *button in _buttons) {
        [button setImageEdgeInsets:imageInsets];
        
    }
}

- (void)setSelectedFlow:(BOOL)selectedFlow {
    _selectedFlow = selectedFlow;
    [self adjustSubViewsFrame];
    _flowView.hidden = !selectedFlow;
}

- (void)setShadowPosition:(SegmentedControlShadowPosition)shadowPosition {
    _shadowPosition = shadowPosition;
    CGFloat height = 1.0 / [UIScreen mainScreen].scale;
    
    if (!_shadowLine) {
        _shadowLine = [[UIView alloc] init];
        _shadowLine.backgroundColor = COLOR_CELL_LINE;
        [self addSubview:_shadowLine];
    }
    _shadowLine.height = height;
    _shadowLine.width = self.width;
    if (shadowPosition == SegmentedControlShadowPositionTop) {
        _shadowLine.top = 0;
    } else if (shadowPosition == SegmentedControlShadowPositionBottom) {
        _shadowLine.bottom = self.height;
    } else {
        _shadowLine.height = 0;
    }
}

- (void)setSeparatorHidden:(BOOL)separatorHidden {
    _separatorHidden = separatorHidden;
    for (UIView *view in _separatorViews) {
        view.hidden = _separatorHidden;
    }
}

- (void)setSelectedFlowColor:(UIColor *)selectedFlowColor {
    _selectedFlowColor = selectedFlowColor;
    _flowView.backgroundColor = _selectedFlowColor;
}

- (void)setCustomFlowRectInButton:(CGRect)customFlowRectInButton {
    _customFlowRectInButton = customFlowRectInButton;
    [self adjustSubViewsFrame];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint pointOfTouch = [[[event touchesForView:self] anyObject] locationInView:self];
    float x = floorf(pointOfTouch.x /(kScreenWidth/2.));
    if (self.delgate && [self.delgate respondsToSelector:@selector(selectBtnWithIndex:)]) {
        [self.delgate selectBtnWithIndex:[[NSNumber numberWithFloat:x] integerValue]];
    }
}

@end
